package com.example.mobile2021606145zbq0618;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class MyDateAdapter {
    private MySQLiteOpenHelper openHelper;
    private SQLiteDatabase database;
    public void openDB(Context context){
        openHelper=new MySQLiteOpenHelper(context,"student.db",null,1);
        try {
            database=openHelper.getWritableDatabase();
        }catch (Exception e){
            database=openHelper.getReadableDatabase();
        }
    }
    public void closeDB(){
        if (database!=null){
            database.close();
            database=null;
        }
        if (openHelper!=null){
            openHelper.close();
            openHelper=null;
        }
    }
    public List<Users> QueryAll(Context context){
        List<Users> usersList=new ArrayList<>();
        openDB(context);
        Cursor cursor = database.query("users",null,null,null,null,null,null,null);
    if (cursor.moveToFirst()){
        do {
            int id=cursor.getInt(0);
            String name=cursor.getString(1);
            int age=cursor.getInt(2);
            float score=cursor.getFloat(3);
            usersList.add(new Users(id, name, age, score));
        }while (cursor.moveToNext());
    }
    cursor.close();
    closeDB();
    return usersList;
    }
    public long insert(Context context,Users users){
        openDB(context);
        ContentValues values = new ContentValues();
        values.put("name", users.getName());
        values.put("age", users.getAge());
        values.put("score", users.getScore());
        long result = database.insert("users",null,values);
        closeDB();
        return result;
    }

    public void delete(Context context, int id) {

    }

    public void update(Context context, int id, Users users) {
    }
}
